var express = require('express');
var BufferHelper = require('bufferhelper');
var request = require('request');
var fs = require('fs');
var speakeasy = require('speakeasy');
var passwordHash = require('password-hash');

var router = express.Router();

var UserAccountEntity = require("../models/UserAccount").UserAccountEntity;
var VerificationCodeEntity = require("../models/VerificationCode").VerificationCodeEntity;

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});


router.post('/register', function(req, res, next) {

    var mobile = req.body.mobile;
    var password = req.body.password;

    UserAccountEntity.findOne({mobile:mobile},function (err, user) {
        if (err){
            res.send(err);
            return;
        }
        if (user){
            res.send("该手机号已注册!");
        }else{
            var userAc = new UserAccountEntity({
                mobile:mobile,
                password:password
            })

            userAc.save(function (err, userAccount) {
                if (err){
                    res.send(err);
                    return;
                }

                if (userAccount){
                    var key = speakeasy.generateSecret({});
                    var url = "otpauth://totp/"+mobile+"?secret="+key.base32;
                    var verified = new VerificationCodeEntity({
                        mobile:userAccount.mobile,//手机号
                        ascii:key.ascii,
                        hex:key.hex,
                        base32:key.base32,//验证码
                        otpauth_url:url,
                        uid:userAccount._id//注册成功则记录关联的用户账户ID
                    })

                    verified.save(function (err, doc) {

                        if (err){
                            res.send(err);
                            return;
                        }

                        if (doc){
                            var codeBuffer = new BufferHelper();
                            request.get({
                                    url: "http://qr.liantu.com/api.php?&w=400&text=" + doc.otpauth_url
                                }
                            )
                                .on('error', function (err) {
                                    console.log(err);
                                })
                                .on('data', function (chunck) {
                                    codeBuffer.concat(chunck);
                                })
                                .on('end', function () {
                                    var con = codeBuffer.toBuffer();
                                    fs.writeFileSync('qrCode.jpg', con);
                                    res.send("success!")
                                })
                            ;
                        }

                    })

                }

            })
        }
    });
});

router.post('/login', function(req, res, next) {

    var mobile = req.body.mobile;
    var password = req.body.password;
    var userToken = req.body.userToken;

    UserAccountEntity.findOne({mobile:mobile},function (err, user) {
        if (err){
            res.send(err);
            return;
        }
        if (user){

            if (user.password != password){
                res.send("密码错误");
            }else{
                VerificationCodeEntity.findOne({mobile:mobile},function (err, doc) {
                    if (err){
                        res.send(err);
                        return;
                    }
                    if (doc){
                        var verified = speakeasy.totp.verify({ secret: doc.base32,
                            encoding: 'base32',
                            token: userToken });
                        if (verified){
                            res.send("登陆成功");
                        }else{
                            res.send("验证失败");
                        }

                    }else{
                        res.send("错误");
                    }
                })
            }


        }else{
            res.send("无该账号信息,此号码未注册");
        }
    })

});

// router.get('/getKey', function(req, res, next) {
//
//     var codeBuffer = new BufferHelper();
//     request.get({
//             url: "http://qr.liantu.com/api.php?&w=400&text=" + key.otpauth_url,
//         }
//     )//获取验证码
//         .on('error', function (err) {
//             console.log(err);
//         })
//         .on('data', function (chunck) {
//             codeBuffer.concat(chunck);
//         })
//         .on('end', function () {
//             var con = codeBuffer.toBuffer();
//             fs.writeFileSync('code.jpg', con);
//             // console.log(con);
//             // re.send(con);
//         });
//     res.send('respond with a resource');
// });

module.exports = router;
